//
//  CZEmoticonTools.swift
//  WeiBo
//
//  Created by Apple on 16/9/9.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
//  一页显示20
private let numbersOfPage = 20
//  表情读取专用类
class CZEmoticonTools: NSObject {

    //  单例全局访问点
    static let shareTools: CZEmoticonTools = CZEmoticonTools()
    //  构造函数私有化
    private override init() {
        super.init()
        
        
    }
    
    //  创建表情bundle对象
    private lazy var emoticonBundle: Bundle = {
        //  创建bundle路径
        let path = Bundle.main.path(forResource: "Emoticons", ofType: "bundle")!
        //  根据path创建bundle对象
        let bundle = Bundle(path: path)!
        
        return bundle
    
    }()
    
    //  最近表情
    private lazy var recentEmoticonArray: [CZEmoticon] = {
        //  先从本地查找
        if let recentArray = self.loadRecentEmoticonArray() {
            
            var tempArray = [CZEmoticon]()
            //  图片路径修改
            for emoticon in recentArray {
            
                //  判断type如果是图片，那么设置一下路径
                if emoticon.type == "0" {
                    
                    //  重新根据指定文件获取路径
                    var deleteLastFileName = (emoticon.path! as NSString).deletingLastPathComponent
                    
                    let range = (deleteLastFileName as NSString).range(of: "/", options: NSString.CompareOptions.backwards)
                    
                    
                    
                    //  截取子路径
                    let subPath = (deleteLastFileName as NSString).substring(from: range.location + 1)
                    let newPath = self.emoticonBundle.path(forResource: subPath, ofType: nil)! + "/" + emoticon.png!
                    emoticon.path = newPath
                    
                    
                }
                tempArray.append(emoticon)
                
            }
            
           return tempArray
        } else {
            return [CZEmoticon]()
        }
    
    }()
    
    //  默认表情
    private lazy var defaultEmoticonArray: [CZEmoticon] = {
       
        return self.loadEmotionArray(subPath: "default/info.plist")
        
    }()
    
    //  emoji表情
    private lazy var emojiEmoticonArray: [CZEmoticon] = {
        
        return self.loadEmotionArray(subPath: "emoji/info.plist")
        
    }()
    //  浪小花表情
    private lazy var lxhEmoticonArray: [CZEmoticon] = {
        
        return self.loadEmotionArray(subPath: "lxh/info.plist")
        
    }()
    
    lazy var allEmoticonArray: [[[CZEmoticon]]] = {
    
        return [
            
            self.sectionEmoticons(emoticons: self.recentEmoticonArray),
            self.sectionEmoticons(emoticons: self.defaultEmoticonArray),
            self.sectionEmoticons(emoticons: self.emojiEmoticonArray),
            self.sectionEmoticons(emoticons: self.lxhEmoticonArray)
        ]
        
    }()
    
    
    //  根据子路径读取数据
    private func loadEmotionArray(subPath: String) -> [CZEmoticon] {
        
        let infoPath = self.emoticonBundle.path(forResource: subPath, ofType: nil)!
        //  读取文件的数据
        let emoticonDicArray = NSArray(contentsOfFile: infoPath)!
        
        var tempArray = [CZEmoticon]()
        //  遍历数据进行字典转模型
        for emoticonDic in emoticonDicArray {
            let emoticon = CZEmoticon(dic: emoticonDic as! [String : Any])
            //  如果是0表示图片，那么设置图片全路径
            if emoticon.type == "0" {
                //  删除后缀文件
                let lastInfoPath = (infoPath as NSString).deletingLastPathComponent
                //  info.plist 上一级目录 + 图片名 
                emoticon.path = lastInfoPath + "/" + emoticon.png!
            }
            tempArray.append(emoticon)
        }
        return tempArray
    }
    
    //  根据表情数组元素，拆分成二维数组
    private func sectionEmoticons(emoticons: [CZEmoticon]) -> [[CZEmoticon]] {
        
        //  计算分成多少页显示
        let pageCount = (emoticons.count - 1) / numbersOfPage + 1
        
        var tempArray: [[CZEmoticon]] = [[CZEmoticon]]()
        //  根据页数分数据
        for pageIndex in 0..<pageCount {
            
            let loc = pageIndex * numbersOfPage
            var length = numbersOfPage
            
            if loc + length > emoticons.count {
                length = emoticons.count - loc
            }
            
            let subArray = (emoticons as NSArray).subarray(with: NSMakeRange(loc, length))

            tempArray.append(subArray as! [CZEmoticon])
            
        }
        
        return tempArray
    }
    
    //  保存最近数据
    func saveRecentEmoticon(emoticon: CZEmoticon) -> Void {
        
        //  查找原有最近表情数组里面是已经存在了表情
        
        //  如果存在了则把之前的表情删除掉把新添加的表情添加到第一个位置
        
        //  最近表情只存储20个表情数据，超出把最后一个元素删除掉
        
        //  记录删除的表情数组数据
        var tempArray = [CZEmoticon]()
        for (i, value) in recentEmoticonArray.enumerated() {
            
            //  判断表情类型如果图片->判断图片名称，如果是emoji->判断code
            if value.type == "0" {
            
                if value.png == emoticon.png {
                    
                    tempArray.append(value)
                
                    //  删除
                    recentEmoticonArray.remove(at: i)
                    break
                }
                
            } else {
            
                if value.code == emoticon.code {
                    
                    tempArray.append(value)
                    //  删除
                    recentEmoticonArray.remove(at: i)
                    break
                }
                
            }
            
            
        }
        
        //  插入到最近表情数组的第一个元素
        recentEmoticonArray.insert(emoticon, at: 0)
        
        //  如果超过20个表情那么删除后面的表情
        while recentEmoticonArray.count > 20 {
            
            //  删除最后一个元素
            recentEmoticonArray.removeLast()
            
        }
        
        //  更新一下最近表情的数据
        allEmoticonArray[0][0] = recentEmoticonArray
        
        //  归档当前对象
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticonArray.archive")
        
        NSKeyedArchiver.archiveRootObject(recentEmoticonArray, toFile: path)
    }
    
    
    //  读取当前对象
    func loadRecentEmoticonArray() -> [CZEmoticon]? {
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticonArray.archive")
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [CZEmoticon]
    }
    
    
    //  根据表情描述查找表情模型
    func findEmotion(chs: String) -> CZEmoticon? {
        
        //  在默认表情和浪小花表情中查找
        for value in defaultEmoticonArray {
            if value.chs == chs {
                return value
            }
        }

        for value in lxhEmoticonArray {
            if value.chs == chs {
                return value
            }
        }
        
        return nil
        
    }
    
    
    
    
    
}
